﻿using System;
using System.Windows;
using System.Windows.Data;
using System.Text.RegularExpressions;

namespace AncheStart.Converter
{
    public class DecimalConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (null == value)
                return DependencyProperty.UnsetValue;
            else
            {
                var success = Double.TryParse(value.ToString(), out double result);
                return (success && result != 0) ? Math.Round(result, 3) : value;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //if (value.ToString().EndsWith("."))
            //{
            //可以输入“.”或者“,”，原理是使其报错则不对binding的变量赋值
            string result = (value.ToString().EndsWith(".") ? "." : value).ToString();
            result = (result.ToString().EndsWith(",") ? "," : result).ToString();
            //可以输入末尾是0的小数，原理同上
            Regex re = new Regex("^([0-9]{1,}[.,][0-9]*0)$");
            result = re.IsMatch(result) ? "." : result;
            if (string.IsNullOrEmpty(result)) return null;
            return string.IsNullOrEmpty(result) ? DependencyProperty.UnsetValue : result;
            //}
            //else
            //    return value;
        }
    }
}